package xin.nick.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import xin.nick.entity.Role;
import xin.nick.entity.UserRole;
import xin.nick.mapper.RoleMapper;
import xin.nick.mapper.UserRoleMapper;
import xin.nick.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author Nick
 * @since 2022-08-09
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 根据用户id获取角色key列表
     * @param userId
     * @return
     */
    @Override
    public List<String> getRoleKeyListByUserId(Long userId) {

        // 获取到角色列表,遍历出 roleKey
        List<Role> roleList = getRoleListByUserId(userId);
        if (CollectionUtils.isEmpty(roleList)) {
            return new ArrayList<>();
        }
        List<String> roleKeyList = roleList.parallelStream().filter(Objects::nonNull).map(Role::getRoleKey).collect(Collectors.toList());

        return roleKeyList;
    }

    /**
     * 根据用户id获取角色列表
     * @param userId
     * @return
     */
    @Override
    public List<Role> getRoleListByUserId(Long userId) {

        if (Objects.isNull(userId)) {
            return new ArrayList<>();
        }

        // 首先从用户-角色关联中拿到角色id列表,之后获取角色列表
        LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userRoleLambdaQueryWrapper.eq(UserRole::getUserId, userId);
        List<UserRole> userRoleList = userRoleMapper.selectList(userRoleLambdaQueryWrapper);
        if (CollectionUtils.isEmpty(userRoleList)) {
            return new ArrayList<>();
        }
        List<Long> roleIdList = userRoleList.parallelStream().filter(Objects::nonNull).map(UserRole::getRoleId).collect(Collectors.toList());

        // 获取到角色列表,
        List<Role> roleList = listByIds(roleIdList);
        return roleList;
    }
}
